<?php

namespace app\admin\controller\vppz;


use think\Exception;

use \app\admin\model\vppz\MedicationPlan as MedicationPlanModel;
use \app\admin\model\vppz\MedicalInformation as MedicalInformationModel;
use \app\admin\model\vppz\HealthNote as HealthNoteModel;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class FamilyManage extends Base
{

    /**
     * Service模型对象
     * @var \app\admin\model\vppz\FamilyMembers
     */
    protected $model = null;

	protected $searchFields = ['id','name'];
    protected $user_id = '';
    protected $types = array(
        'outpatient'=>'门诊病历',
        'prescription'=>'门诊处方',
        'discharge'=>'出院记录',
        'physical'=>'体检报告',
        'report'=>'报告单'
    );
    protected $guidances = array(
        'before'=>'餐前',
        'after'=>'餐后',
        'empty'=>'空腹',
        'with'=>'随餐服用',
        'sleep'=>'睡前'
    );
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vppz\FamilyMembers;
        $this->MedicationPlanModel = new MedicationPlanModel;
        $this->MedicalInformationModel = new MedicalInformationModel;
        $this->HealthNoteModel = new HealthNoteModel;
    }

/**
     * 查看
     */
    public function index()
    {
        $ids = input('ids');
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $info = $this->model->where(['id'=>$ids])->find();
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            $sexs = array(
                '1'=>'男',
                '2'=>'女',
                '3'=>'其他'
            );
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                    ->where($where)->where(['is_self'=>0,'user_id'=>$info['user_id']])
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                $row->sex = $sexs[$row->gender]??'未知';
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('user_id',$ids);
        return $this->view->fetch();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
/**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $data = $row->toArray();
        // 获取就诊资料
        $medicalRecords = $this->MedicalInformationModel->where('family_id', $ids)->order('date','desc')->select();

        if(empty($medicalRecords) === FALSE){
            foreach ($medicalRecords as &$v){
                $images = json_decode($v['image'],true);
                if(empty($images) === FALSE){
                    foreach ($images as &$imagev){
                        $imagev = \addons\vppz\library\Vpower::dourl($imagev);
                    }
                    $v['images'] = $images;
                }
                $v['type_name'] = $this->types[$v['type']];
            }
        }
        // 获取用药计划
        $medicationPlans = $this->MedicationPlanModel->where('family_id', $ids)
            ->order('createtime','desc')->select();
        if(empty($medicationPlans) === FALSE){
            foreach ($medicationPlans as &$v){
                if(empty($v['guidance']) === FALSE) {
                    $v['guidance'] = $this->guidances[$v['guidance']];
                }
            }
        }
        // 获取健康史
        $reshealthHistoryjiazu = [];
        $healthHistoryjiazu = $this->HealthNoteModel->where('family_id', $ids)->where('type',1)->find();
        if(empty($healthHistoryjiazu)===FALSE){
            $jiazu = json_decode($healthHistoryjiazu['content'],true);
            if($jiazu['hasFamilyHistory']){
                $reshealthHistoryjiazu = $jiazu['customDiseases'];
            }
        }
        $healthHistorygeren = $this->HealthNoteModel->where('family_id', $ids)->where('type',2)->find();
        $reshealthHistorygeren = [
            '不喝酒','不吸烟'
        ];
        if(empty($healthHistorygeren)===FALSE){
            $healthHistorygeren=$healthHistorygeren->toArray();
            $content = json_decode($healthHistorygeren['content'],true);
            if($content['drinking']['hasDrinking'] == 'yes'){
                $reshealthHistorygeren[0] = '喝酒('.$content['drinking']['years'].')';
            }
            if($content['smoking']['hasSmoking'] == 'yes'){
                $reshealthHistorygeren[1] = '吸烟('.$content['smoking']['years'].')';
            }
        }
        $healthHistoryjiwang = $this->HealthNoteModel->where('family_id', $ids)->where('type',3)->find();
        $healthHistoryjiwangcustomDiseases = [];
        $healthHistoryjiwangsurgery = [];
        $healthHistoryjiwangallergy = [];
        $healthHistoryjiwangmedication = [];
        if (empty($healthHistoryjiwang) === FALSE){
            $healthHistoryjiwang = $healthHistoryjiwang->toArray();
            $content = json_decode($healthHistoryjiwang['content'],true);
            if($content['disease']['hasDisease'] == 'yes'){
                $healthHistoryjiwangcustomDiseases = $content['disease']['customDiseases'];
            }
            if($content['surgery']['hasSurgery'] == 'yes'){
                $healthHistoryjiwangsurgery = $content['surgery']['surgeries'];
            }
            if($content['allergy']['hasAllergy'] == 'yes'){
                $healthHistoryjiwangallergy = $content['allergy']['customAllergens'];
            }
            if($content['medication']['hasMedication'] == 'yes'){
                $healthHistoryjiwangmedication = $content['medication']['medications'];
            }
        }
        $sexs = array(
                '1'=>'男',
                '2'=>'女',
                '3'=>'其他'
            );

        $this->assign([
            'medicalRecords' => $medicalRecords,
            'medicationPlans' => $medicationPlans,
            'healthHistoryjiazu' => $reshealthHistoryjiazu,
            'healthHistorygeren' => $reshealthHistorygeren,
            'healthHistoryjiwangcustomDiseases' => $healthHistoryjiwangcustomDiseases,
            'healthHistoryjiwangsurgery' => $healthHistoryjiwangsurgery,
            'healthHistoryjiwangallergy' => $healthHistoryjiwangallergy,
            'healthHistoryjiwangmedication' => $healthHistoryjiwangmedication,
        ]);
        $data['gender'] = $sexs[$data['gender']]??'未知';
        $this->view->assign("userInfo", $data);
        return $this->view->fetch();
    }
}
